package point

import (
	"bufio"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

type NtpServerPoint struct{}

func NewNtpServerPoint() *NtpServerPoint { return &NtpServerPoint{} }

func (m *NtpServerPoint) Get() any {

	getNtpServer := func() string {
		cmd := exec.Command("timedatectl", "show-timesync")
		out, err := cmd.Output()
		if err != nil {
			fmt.Println("exec timedatectl show-timesync failed")
			return ""
		}

		lines := strings.Split(string(out), "\n")

		for _, line := range lines {
			if strings.HasPrefix(line, "ServerName=") {
				return strings.TrimPrefix(line, "ServerName=")
			}
		}

		return ""
	}

	return getNtpServer()
}

func (m *NtpServerPoint) Set(val ...any) bool {

	if len(val) < 1 {
		return false
	}

	setNtpServerToFile := func(filePath, ntpServer string) bool {
		file, err := os.Open(filePath)
		if err != nil {
			fmt.Println("open file failed, file name -->", filePath, "err -->", err)
			return false
		}

		var lines []string

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			line := scanner.Text()
			if strings.Contains(line, "NTP=") {
				line = "NTP=" + ntpServer
			}
			lines = append(lines, line)
		}

		if err := scanner.Err(); err != nil {
			fmt.Println("Error reading file:", err)
			file.Close()
			return false
		}

		file.Close()

		file, err = os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
		if err != nil {
			fmt.Println("Error opening file for writing:", err)
			return false
		}
		defer file.Close()

		writer := bufio.NewWriter(file)
		for _, line := range lines {
			writer.WriteString(line + "\n")
		}
		writer.Flush()

		return true
	}

	restartNtpServer := func() bool {
		return exec.Command("systemctl", "restart", "systemd-timesyncd").Run() == nil
	}

	if url, ok := val[0].(string); ok {
		return setNtpServerToFile("/etc/systemd/timesyncd.conf", url) && restartNtpServer()
	}

	return false
}

func (m *NtpServerPoint) SetRoute(string) PointInterface { return m }
